package com.wbs.controller;

import com.alibaba.fastjson.JSON;
import  com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.sun.org.apache.regexp.internal.RE;
import com.wbs.resutil.Result;
import com.wbs.vo.RefundQueryVO;
import com.wbs.vo.RefundVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @Author: 芝梦
 * @Description: 支付功能控制层
 * @DateTime: 2024/3/1 16:50
 */
@RequestMapping("pay")
@RestController
public class PayController {
    @Autowired
    AlipayClient alipayClient;

    //收单下单并支付页面接口
    @GetMapping("aliPay")
    public String aliPay(@RequestParam String out_trade_no, @RequestParam String total_amount, @RequestParam String subject){
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
//异步接收地址，仅支持http/https，公网可访问
        request.setNotifyUrl("http://5d3b736d.r8.cpolar.top/ny/notifyUrl");   //post 异步回调 用于异步返回支付是否成功的结果 确保支付成功 在界面可以完成属于自己的逻辑 通过这个回调就可以使用异步的方式指导是否支付成功
//同步跳转地址，仅支持http/https
        request.setReturnUrl("http://5d3b736d.r8.cpolar.top/ny/returnUrl");   //get请求 同步回调 用于支付成功后可以跳转到商家自己页面 但不能保证真的支付成功
/******必传参数******/
        JSONObject bizContent = new JSONObject();
//商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no", out_trade_no);
//支付金额，最小值0.01元
        bizContent.put("total_amount", total_amount);
//订单标题，不可使用特殊符号
        bizContent.put("subject", subject);
//电脑网站支付场景固定传值FAST_INSTANT_TRADE_PAY
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

/******可选参数******/
        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request,"POST");
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
// 如果需要返回GET请求，请使用
        String pageRedirectionData = response.getBody();
        System.out.println(pageRedirectionData);

        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return response.getBody();
    }

    //支付查询接口
    @GetMapping("tradeQuery")
    public Result tradeQuery(@RequestParam String tradeNo){
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

       /* request.setBizContent("{" +
                "  \"out_trade_no\":\"20150320010101001\"," +
                "  \"trade_no\":\"2014112611001004680 073956707\"," +
                "  \"query_options\":[" +
                "    \"trade_settle_info\"" +
                "  ]" +
                "}");*/
        /*获取参数 我们只需要订单编号 更改记录参数的方式 提示为一下*/
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("trade_no",tradeNo);
        request.setBizContent(JSONObject.toJSONString(jsonObject));

        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return Result.SUCCESS().setData(response.getBody());
    }

    //退款接口
    @GetMapping("tradeRefund")
    public Result tradeRefund(@RequestParam String tradeNo, @RequestParam String refundAmount, @RequestParam String outRequestNo){
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("refund_amount", refundAmount);
        bizContent.put("out_request_no", outRequestNo);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            Object alipay_trade_refund_response = jsonObject.get("alipay_trade_refund_response");
            String s = JSONObject.toJSONString(alipay_trade_refund_response);
            RefundVO refundVO = JSONObject.parseObject(s, RefundVO.class);
            //判断
            if (!Objects.equals(refundVO.getFund_change(), "Y")){
                //调用退款查询接口
                RefundQueryVO refundQueryVO = getRefundVO(tradeNo, outRequestNo);
                if (Objects.equals(refundQueryVO.getRefund_status(), "REFUND_SUCCESS")){
                    return Result.SUCCESS().setData("相同请求不能二次退款");
                }else {
                    return Result.SUCCESS().setData("退款失败");
                }
            }else {
                return Result.SUCCESS().setData("退款成功");
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;

/*        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("refund_amount", refundAmount);
        bizContent.put("out_request_no", outRequestNo);

//// 返回参数选项，按需传入
//JSONArray queryOptions = new JSONArray();
//queryOptions.add("refund_detail_item_list");
//bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
            System.out.println(response.getBody());
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }

        return null;*/
    }

    //退款查询接口
    public RefundQueryVO getRefundVO(String tradeNo, String outRequestNo){
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", tradeNo);
        bizContent.put("out_request_no", outRequestNo);

//// 返回参数选项，按需传入
//JSONArray queryOptions = new JSONArray();
//queryOptions.add("refund_detail_item_list");
//bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
            String body = response.getBody();
            JSONObject jsonObject = JSONObject.parseObject(body);
            Object alipay_trade_fastpay_refund_query_response = jsonObject.get("alipay_trade_fastpay_refund_query_response");
            String S = JSONObject.toJSONString(alipay_trade_fastpay_refund_query_response);
            RefundQueryVO refundQueryVO = JSONObject.parseObject(S, RefundQueryVO.class);
            return refundQueryVO;
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }
}
